package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.common.qcloud.qcloudcos.CosConstants;
import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.MesSaleOrderChangeManageService;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.MesSaleOrderManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.MesSaleOrderChangeDTO;
import com.hunttown.mes.rpc.domain.MesSaleOrderDTO;
import com.hunttown.mes.rpc.domain.query.MesSaleOrderChangeDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.mes.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * created by wangjunfu on 2022-09-08 15:57:30
 */
@Controller
@RequestMapping(value = "/mes/order-change")
public class MesSaleOrderChangeController {

    private final static Logger logger = LoggerFactory.getLogger(MesSaleOrderChangeController.class);

    private final MesSaleOrderChangeManageService mesSaleOrderChangeService;
    private final MesSaleOrderManageService mesSaleOrderService;
    private final AnalysisManageManageService manageService;
    private final ModelService modelService;

    @Autowired
    public MesSaleOrderChangeController(MesSaleOrderChangeManageService mesSaleOrderChangeService, MesSaleOrderManageService mesSaleOrderService, AnalysisManageManageService manageService, ModelService modelService) {
        this.mesSaleOrderChangeService = mesSaleOrderChangeService;
        this.mesSaleOrderService = mesSaleOrderService;
        this.manageService = manageService;
        this.modelService = modelService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return model
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, MesSaleOrderChangeDTOQuery dtoQuery) {

        //获取销售订单
        MesSaleOrderDTO orderObj = mesSaleOrderService.getById(dtoQuery.getOrderId());
        if (orderObj == null) {
            throw new RuntimeException("未查询到销售订单信息");
        }
        model.addAttribute("orderObj", orderObj);

        dtoQuery.setOrderBy("order by id desc");
        Page<MesSaleOrderChangeDTO> dataPage = mesSaleOrderChangeService.getForPage(dtoQuery);
        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "mes/order-change/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return model
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(HttpServletRequest request, Model model, Integer id, Integer orderId) {
        id = (id == null ? 0 : id);

        if (orderId == null || orderId <= 0) {
            throw new RuntimeException("未查询到销售订单信息");
        }

        //获取销售订单
        MesSaleOrderDTO orderObj = mesSaleOrderService.getById(orderId);
        if (orderObj == null) {
            throw new RuntimeException("未查询到销售订单信息");
        }
        model.addAttribute("orderObj", orderObj);

        MesSaleOrderChangeDTO obj;

        if (id > 0) {
            obj = mesSaleOrderChangeService.getById(id);
            obj.setCompanyName(modelService.getCompanyName(obj.getCompanyId()));

            //region 获取已上传文件
            modelService.getUploadPage(model, obj.getContractDoc());
            model.addAttribute("mainPicId", 0); //主图
            //endregion

        } else {
            obj = new MesSaleOrderChangeDTO();
            obj.setId(0);
            obj.setOrderId(orderId);
            obj.setCompanyId(orderObj.getCompanyId());
            obj.setCompanyName(modelService.getCompanyName(orderObj.getCompanyId()));
            obj.setProposeType(1);
            obj.setLinkId(orderObj.getLinkId());
            obj.setLinkName(orderObj.getLinkName());
            obj.setLinkMobile(orderObj.getLinkMobile());

            String pin = AdminBaseClass.getPin(request);
            AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
            obj.setOperator(curr_obj.getId());
            obj.setOperateDate(new Date());
            obj.setStatus(1);
        }
        model.addAttribute("Obj", obj);

        //经办人
        modelService.getManagerPage(model);

        //region 文件上传使用
        model.addAttribute("uploadTableName", "mes_sale_order_change");
        model.addAttribute("uploadRecordId", obj.getId());
        model.addAttribute("labelTips", "合同上传");
        model.addAttribute("btnTips", "上传合同");
        model.addAttribute("modalTips", "合同上传");

        String uploadPrefix = CosConstants.getStorageFolder(null);
        model.addAttribute("uploadPrefix", uploadPrefix);
        //endregion

        return "mes/order-change/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return json
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, MesSaleOrderChangeDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            //日期
            objDTO.setOperateDate(DateConvertUtils.strToDate(objDTO.getOperateDateSr()));

            //处理上传ID
            objDTO.setContractDoc(FormatUtils.formatCommas(objDTO.getIsUpload()));

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = mesSaleOrderChangeService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                Boolean isNext = mesSaleOrderChangeService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return json
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = mesSaleOrderChangeService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return json
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = mesSaleOrderChangeService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 数据查看

    /**
     * 数据查看
     *
     * @param model     model模型
     * @param id        主键id
     * @param tableName 数据库英文表名
     * @return model
     */
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    public String show(Model model, Integer id, String tableName) {
        id = (id == null ? 0 : id);

        MesSaleOrderChangeDTO obj = new MesSaleOrderChangeDTO();
        obj.setId(id);

        if (id > 0) {
            obj = mesSaleOrderChangeService.getById(id);
        }
        mesSaleOrderChangeService.assembleObjInfo(model, tableName, obj);

        return "show/show-template";
    }

    //endregion

}